<script setup>
	import { computed, ref, watch } from 'vue'
	import { SettingOutlined, PlusOutlined, DeleteOutlined, InfoCircleOutlined } from '@ant-design/icons-vue'
	import { useApiDatasetStore } from '@/views/plugin/dashboard/store/apiDataset'
	import { message } from 'ant-design-vue'

	const emit = defineEmits(['change'])
	const store = useApiDatasetStore()

	// 参数表单数据
	const parameterList = ref([])
	const showAdvanced = ref(false)

	// 支持的系统变量
	const systemVariables = [
		{ label: '当前用户ID', value: '${current_user_id}', description: '当前登录用户的ID' },
		{ label: '当前用户名', value: '${current_user_name}', description: '当前登录用户的用户名' },
		{ label: '当前用户部门ID', value: '${current_user_dept_id}', description: '当前登录用户的部门ID' },
		{ label: '当前用户部门名称', value: '${current_user_dept_name}', description: '当前登录用户的部门名称' },
		{ label: '当前日期', value: '${current_date}', description: '当前日期 (YYYY-MM-DD)' },
		{ label: '当前时间', value: '${current_datetime}', description: '当前日期时间 (YYYY-MM-DD HH:mm:ss)' },
		{ label: '当前时间戳', value: '${current_timestamp}', description: '当前时间戳 (毫秒)' }
	]

	// 当前选中的API信息
	const selectedApiInfo = computed(() => {
		return store.selectedApiInfo
	})

	// 常用公式列表
	const commonFormulas = ref([
		{ key: 'current_user_id', label: '当前用户ID', value: '${current_user_id}' },
		{ key: 'current_time', label: '当前时间', value: '${current_time}' },
		{ key: 'current_date', label: '当前日期', value: '${current_date}' },
		{ key: 'page_size', label: '分页大小', value: '10' },
		{ key: 'page_num', label: '页码', value: '1' }
	])

	// 全选状态计算
	const allChecked = computed(() => {
		return parameterList.value.length > 0 && parameterList.value.every(param => param.enabled)
	})

	const indeterminate = computed(() => {
		const checkedCount = parameterList.value.filter(param => param.enabled).length
		return checkedCount > 0 && checkedCount < parameterList.value.length
	})

	// 初始化参数列表
	const initParameterList = () => {
		const apiParams = store.formData.itemConfig.apiParams || {}
		parameterList.value = Object.entries(apiParams).map(([key, value]) => ({
			id: Date.now() + Math.random(),
			name: key,
			value: value,
			type: 'string',
			enabled: true,
			description: ''
		}))

		// 如果没有参数且API有定义参数，则自动添加
		if (parameterList.value.length === 0 && selectedApiInfo.value?.parameters) {
			selectedApiInfo.value.parameters.forEach((param) => {
				parameterList.value.push({
					id: Date.now() + Math.random(),
					name: param.name,
					value: param.required ? '' : param.defaultValue || '',
					type: param.type || 'string',
					enabled: true,
					required: param.required,
					description: param.description || ''
				})
			})
		}
	}

	// 添加参数
	const addParameter = () => {
		parameterList.value.push({
			id: Date.now() + Math.random(),
			name: '',
			value: '',
			type: 'string',
			enabled: true,
			description: ''
		})
	}

	// 添加常用参数
	const addCommonParam = (formula) => {
		parameterList.value.push({
			id: Date.now() + Math.random(),
			name: formula.key,
			value: formula.value,
			type: 'string',
			enabled: true,
			description: formula.label
		})
		updateApiParams()
	}

	// 切换全选
	const toggleAllParams = (e) => {
		const checked = e.target.checked
		parameterList.value.forEach(param => {
			param.enabled = checked
		})
		updateApiParams()
	}

	// 删除参数
	const removeParameter = (index) => {
		parameterList.value.splice(index, 1)
		updateApiParams()
	}

	// 更新API参数
	const updateApiParams = () => {
		const apiParams = {}
		parameterList.value.forEach((param) => {
			if (param.name && param.name.trim() && param.enabled) {
				apiParams[param.name.trim()] = param.value
			}
		})
		store.setApiParams(apiParams)
		emit('change')
	}

	// 插入系统变量
	const insertSystemVariable = (variable, paramIndex) => {
		if (parameterList.value[paramIndex]) {
			parameterList.value[paramIndex].value = variable.value
			updateApiParams()
		}
	}

	// 验证参数
	const validateParameters = () => {
		const errors = []
		parameterList.value.forEach((param, index) => {
			if (!param.name || !param.name.trim()) {
				errors.push(`第${index + 1}个参数名称不能为空`)
			}
			if (param.required && (!param.value || !param.value.trim())) {
				errors.push(`参数 ${param.name} 是必填项`)
			}
		})
		return errors
	}

	// 监听API选择变化
	watch(
		() => store.formData.itemConfig.apiPath,
		() => {
			initParameterList()
		},
		{ immediate: true }
	)

	// 监听参数变化
	watch(
		parameterList,
		() => {
			updateApiParams()
		},
		{ deep: true }
	)
</script>

<template>
	<div class="api-parameter-form">
		<!-- 参数表格 -->
		<div class="parameter-table">
			<!-- 表格头部 -->
			<div class="table-header">
				<div class="col-checkbox">
					<a-checkbox
						:checked="allChecked"
						:indeterminate="indeterminate"
						@change="toggleAllParams"
					/>
				</div>
				<div class="col-key">KEY</div>
				<div class="col-value">VALUE</div>
				<div class="col-description">DESCRIPTION</div>
				<div class="col-actions"></div>
			</div>

			<!-- 参数行 -->
			<div class="table-body">
				<div
					v-for="(param, index) in parameterList"
					:key="param.id"
					class="parameter-row"
					:class="{ 'disabled': !param.enabled }"
				>
					<div class="col-checkbox">
						<a-checkbox
							v-model:checked="param.enabled"
							@change="updateApiParams"
						/>
					</div>
					<div class="col-key">
						<a-input
							v-model:value="param.name"
							placeholder="参数名称"
							size="small"
							@change="updateApiParams"
						/>
					</div>
					<div class="col-value">
						<a-input
							v-model:value="param.value"
							placeholder="参数值"
							size="small"
							@change="updateApiParams"
						/>
					</div>
					<div class="col-description">
						<a-input
							v-model:value="param.description"
							placeholder="说明"
							size="small"
							@change="updateApiParams"
						/>
					</div>
					<div class="col-actions">
						<a-button
							danger
							size="small"
							type="text"
							@click="removeParameter(index)"
						>
							<delete-outlined />
						</a-button>
					</div>
				</div>

				<!-- 添加新参数行 -->
				<div class="parameter-row add-row">
					<div class="col-checkbox"></div>
					<div class="col-key">
						<a-input
							placeholder="添加参数名称"
							size="small"
							@pressEnter="addParameter"
						/>
					</div>
					<div class="col-value">
						<a-input
							placeholder="添加参数值"
							size="small"
						/>
					</div>
					<div class="col-description">
						<a-input
							placeholder="添加说明"
							size="small"
						/>
					</div>
					<div class="col-actions"></div>
				</div>
			</div>
		</div>

		<!-- 常用参数（公式）快捷选择 -->
		<div class="common-params-section">
			<div class="section-title">常用参数（公式）</div>
			<div class="common-params-list">
				<a-tag
					v-for="formula in commonFormulas"
					:key="formula.key"
					class="formula-tag"
					@click="addCommonParam(formula)"
				>
					{{ formula.label }}
				</a-tag>
			</div>
		</div>

		<!-- 高级配置 -->
		<div v-if="showAdvanced" class="advanced-section">
			<div class="advanced-title">高级配置</div>

			<!-- JSON格式参数编辑 -->
			<div class="json-editor-section">
				<div class="json-editor-label">JSON格式参数 (高级用户)</div>
				<a-textarea
					:rows="4"
					:value="JSON.stringify(store.formData.itemConfig.apiParams || {}, null, 2)"
					placeholder="{}"
					@change="
						(e) => {
							try {
								const params = JSON.parse(e.target.value)
								store.setApiParams(params)
								emit('change')
							} catch (error) {
								message.error('JSON格式错误')
							}
						}
					"
				/>
			</div>

			<!-- 系统变量说明 -->
			<div class="variables-section">
				<div class="variables-title">支持的系统变量</div>
				<div class="variables-list">
					<div
						v-for="variable in systemVariables"
						:key="variable.value"
						class="variable-info"
					>
						<code class="variable-code">{{ variable.value }}</code>
						<span class="variable-desc">{{ variable.description }}</span>
					</div>
				</div>
			</div>
		</div>

		<!-- 参数验证提示 -->
		<div v-if="selectedApiInfo?.parameters?.length > 0" class="validation-section">
			<div class="validation-title">API参数要求</div>
			<div class="validation-list">
				<div
					v-for="param in selectedApiInfo.parameters"
					:key="param.name"
					class="validation-item"
				>
					<span class="param-name-mono">{{ param.name }}</span>
					<span class="param-type-info">{{ param.type }}</span>
					<span v-if="param.required" class="param-required-info">*</span>
					<span v-if="param.description" class="param-desc-info">- {{ param.description }}</span>
				</div>
			</div>
		</div>
	</div>
</template>

<style scoped>
	.api-parameter-form {
		width: 100%;
	}

	.parameter-table {
		border: 1px solid #f0f0f0;
		border-radius: 6px;
		overflow: hidden;
	}

	.table-header {
		display: grid;
		grid-template-columns: 40px 1fr 1fr 1fr 40px;
		gap: 8px;
		padding: 12px;
		background: #fafafa;
		border-bottom: 1px solid #f0f0f0;
		font-weight: 600;
		font-size: 12px;
		color: #8c8c8c;
		text-transform: uppercase;
	}

	.table-body {
		background: #fff;
	}

	.parameter-row {
		display: grid;
		grid-template-columns: 40px 1fr 1fr 1fr 40px;
		gap: 8px;
		padding: 8px 12px;
		border-bottom: 1px solid #f5f5f5;
		transition: all 0.2s ease;
	}

	.parameter-row:hover {
		background: #fafafa;
	}

	.parameter-row.disabled {
		opacity: 0.5;
		background: #f9f9f9;
	}

	.parameter-row.add-row {
		background: #f8f9fa;
		border-bottom: none;
	}

	.parameter-row.add-row:hover {
		background: #f0f2f5;
	}

	.col-checkbox {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.col-key,
	.col-value,
	.col-description {
		display: flex;
		align-items: center;
	}

	.col-actions {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.common-params-section {
		margin-top: 20px;
		padding-top: 16px;
		border-top: 1px solid #f0f0f0;
	}

	.section-title {
		font-size: 14px;
		font-weight: 600;
		color: #262626;
		margin-bottom: 12px;
	}

	.common-params-list {
		display: flex;
		flex-wrap: wrap;
		gap: 8px;
	}

	.formula-tag {
		cursor: pointer;
		transition: all 0.2s ease;
	}

	.formula-tag:hover {
		background: #e6f7ff;
		border-color: #91d5ff;
		color: #1890ff;
	}

	.advanced-section {
		margin-top: 20px;
		padding-top: 20px;
		border-top: 1px solid #f0f0f0;
		display: flex;
		flex-direction: column;
		gap: 16px;
	}

	.advanced-title {
		font-size: 14px;
		font-weight: 600;
		color: #595959;
	}

	.json-editor-section {
		display: flex;
		flex-direction: column;
		gap: 8px;
	}

	.json-editor-label {
		font-size: 12px;
		color: #8c8c8c;
	}

	.variables-section {
		display: flex;
		flex-direction: column;
		gap: 8px;
	}

	.variables-title {
		font-size: 12px;
		color: #8c8c8c;
	}

	.variables-list {
		display: flex;
		flex-direction: column;
		gap: 4px;
	}

	.variable-info {
		display: flex;
		align-items: center;
		gap: 8px;
		font-size: 12px;
	}

	.variable-code {
		background: #f5f5f5;
		padding: 2px 6px;
		border-radius: 4px;
		font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
		font-size: 11px;
		color: #d63384;
	}

	.variable-desc {
		color: #8c8c8c;
	}

	.validation-section {
		padding: 12px;
		background: #f6f8ff;
		border: 1px solid #e6f0ff;
		border-radius: 8px;
		margin-top: 16px;
	}

	.validation-title {
		font-size: 12px;
		font-weight: 600;
		color: #1890ff;
		margin-bottom: 8px;
	}

	.validation-list {
		display: flex;
		flex-direction: column;
		gap: 4px;
	}

	.validation-item {
		display: flex;
		align-items: center;
		gap: 8px;
		font-size: 12px;
	}

	.param-name-mono {
		font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
		font-weight: 600;
		color: #262626;
	}

	.param-type-info {
		color: #8c8c8c;
		font-style: italic;
	}

	.param-required-info {
		color: #ff4d4f;
		font-weight: bold;
	}

	.param-desc-info {
		color: #8c8c8c;
		flex: 1;
	}

	/* 响应式设计 */
	@media (max-width: 768px) {
		.table-header,
		.parameter-row {
			grid-template-columns: 30px 1fr 1fr 30px;
			gap: 4px;
			padding: 8px;
		}

		.col-description {
			display: none;
		}

		.common-params-list {
			gap: 4px;
		}

		.formula-tag {
			font-size: 12px;
			padding: 2px 6px;
		}
	}
</style>
